package com.victor.controller.mobile;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.victor.entity.FreeTime;
import com.victor.service.FreetimeService;
import com.victor.utils.DateUtils;
import com.victor.utils.Msg;

/**
 * 限时免费管理
 * 
 * @author Mr.Zhang
 *
 */
@RestController
public class FreetimeController {

//	freetime 表名
	@Autowired
	private FreetimeService freetimeService;

//	阅读前判断是否可以阅读，返回1限时免费期间内 3已购买 2是限时免费已过也未购买
	@RequestMapping("/ifFreeTime")
	public Msg ifFreeTime(String userid, String picid) {
		// 更新状态
		freetimeService.updateState();

		// 判断(通过用户id和书id查询freetime表)
		FreeTime free = freetimeService.getFreeByUseridAndPicid(userid, picid);
		if (free != null) {// 如果表中存在数据
			if (free.getState().equals("1")) {
				return Msg.fail("该绘本限时免费时间已过 ");
			} else {
				return Msg.success();
			}
		} else {// 如果表中不存在此数据
			free = new FreeTime();

			free.setUserid(userid);
			free.setPicid(picid);
			free.setStarttime(DateUtils.getNowTime());
			free.setEndtime(DateUtils.getTwoHourAfterTime());
			free.setState("0");

			// 将freetime信息插入数据库
			boolean insResult = freetimeService.addFreeTime(free);
			if (insResult) {
				return Msg.success();
			}
			return Msg.fail();
		}

	}


}
